<?php

namespace App\Http\Middleware;

use App\Constant\Enum;
use App\Models\Setting;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Redis;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\Facades\JWTAuth;

class FrontendAuthenticate
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        config(['auth.defaults.guard' => 'jwt']);
        try {
            $token = JWTAuth::getToken();

            if (empty($token)) {
                return response()->json([
                    'code' => Response::HTTP_UNAUTHORIZED,
                    'message' => 'Token is not provided',
                    'data' => []
                ], Response::HTTP_UNAUTHORIZED);
            }
            if (!$user = JWTAuth::toUser($token)) {
                return response()->json([
                    'code' => Response::HTTP_UNAUTHORIZED,
                    'message' => 'User is not existed',
                    'data' => []
                ], Response::HTTP_UNAUTHORIZED);
            }

            if($user->status != Enum::STATUS_ENABLED) {
                return response()->json([
                    'code' => Response::HTTP_UNAUTHORIZED,
                    'message' => 'Token is expired',
                    'data' => []
                ], Response::HTTP_UNAUTHORIZED);
            }

            $ip = $request->ip();
            $redis = Redis::connection();
            $key = 'ip_users:' . $ip;
            $userId = $user->id;
            $limit = Setting::get('ip_limit') ? intval(Setting::get('ip_limit')): 3;

            if (!$redis->sismember($key, $userId)) {


                if ($redis->scard($key) >= $limit) {
                    return response()->json([
                        'code' => Response::HTTP_FORBIDDEN,
                        'message' => '单个 IP 每天最多只能登录 3 个用户',
                        'data' => []
                    ], Response::HTTP_FORBIDDEN);
                }

                $redis->sadd($key, $userId);

                if (!$redis->ttl($key) || $redis->ttl($key) < 0) {
                    $expireAt = now()->endOfDay()->timestamp;
                    $redis->expireAt($key, $expireAt);
                }
            }

        } catch (TokenExpiredException $e) {
            return response()->json([
                'code' => Response::HTTP_UNAUTHORIZED,
                'message' => 'Token is expired',
                'data' => []
            ], Response::HTTP_UNAUTHORIZED);

        } catch (TokenInvalidException $e) {
            return response()->json([
                'code' => Response::HTTP_UNAUTHORIZED,
                'message' => 'Token is invalid',
                'data' => []
            ], Response::HTTP_UNAUTHORIZED);
        } catch (JWTException $e) {
            return response()->json([
                'code' => Response::HTTP_INTERNAL_SERVER_ERROR,
                'message' => 'Jwt unknown exception',
                'data' => []
            ], Response::HTTP_UNAUTHORIZED);
        }

        return $next($request);
    }
}
